import Vue from "vue"
import VueRouter from "vue-router"
import Layout from '@/pages/layout'
import Home from "../pages/Home.vue"
import orderManageRouter from "./modules/orderManage";
import statistics from "./modules/statistics";
import store from '@/store'
import {Message} from "element-ui";
import CommonMessage from '@/tool/messageCommon'
import {delayTimeScreen} from "@/tool/util";

Vue.use(VueRouter)
//获取原型对象上的push函数
// 防止出现这个路由导航重复的问题
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: "/",
        name: "Home",
        component: Home,
        meta: {
          title: '科友设备维修管理'
        }
      },
      ...orderManageRouter,
      ...statistics
    ]
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../pages/Login.vue"),
    meta: {
      title: '登录'
    }
  },
]

const router = new VueRouter({
  // 返回 savedPosition，在按下 后退/前进 按钮时，就会像浏览器的原生表现那样：
  scrollBehavior(to, from, savePosition) {
    if (savePosition) {
      return savePosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  },
  routes,
})

router.beforeEach( (to, from, next) => {
   const token = store.state.userInfo.userInfo
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (token || to.path === '/login' || to.path.split('/')[1] === 'mobile') {
    next()
  } else {
    delayTimeScreen({message:'界面加载中请稍后'})
    router.push('/login')
  }
})

export default router
